package com.itheima.day05.mybinarysearch;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class Test {
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        int length;
        int start;
        int end;
        System.out.println("请输入您要创建的数组长度：");
        length = sc.nextInt();
        System.out.println("请输入数组中数据的最小值：");
        start = sc.nextInt();
        System.out.println("请输入数组中数据的最大值：");
        end = sc.nextInt();
        int[] arr = getIntArray(length, start, end);
        printArray(arr);
        System.out.println();
        System.out.println("请输入要查咨询的数：");
        int num = sc.nextInt();
        int index = getIndex(arr, num);
        if(index == -1){
            System.out.println("没有");
        }else{
            System.out.println(index);
        }




    }

    public static int[] getIntArray(int length, int start, int end){
        Random r = new Random();
        int[] arr = new int[length];
        end += 1;
        if(start > end){
            start = start + end;
            end = start - end;
            start = start - end;
        }else if(start == end){
            return null;
        }

        // 存数据
        for (int i = 0; i < arr.length; i++) {
            arr[i] = r.nextInt(end - start) + start;
        }

        /*for (int i = 1; i < arr.length; i++) {
            for (int j = 0; j < arr.length - i ; j++) {
                if(arr[j] > arr[j + 1]){
                    arr[j] = arr[j] ^ arr[j + 1];
                    arr[j + 1] = arr[j] ^ arr[j + 1];
                    arr[j] = arr[j] ^ arr[j + 1];
                }
            }
        }*/
        Arrays.sort(arr);
        return arr;

    }

    public static int getIndex(int[] arr, int num){
        int min = 0;
        int max = arr.length - 1;
        while(min <= max){
            int mid = (min + max) >> 1;
            if(num > arr[mid]){
                min = mid + 1;
            }else if(num < arr[mid]){
                max = mid - 1;
            }else{
                return mid;
            }
        }
        return -1;
    }

    public static void printArray(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
